package com.xq.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.xq.entity.TbUser;
import com.xq.exception.BusinessException;
import com.xq.jwt.JwtToken;
import com.xq.redis.RedisUtil;
import com.xq.response.Result01;
import com.xq.response.Result02;
import com.xq.service.TbUserService;
import com.xq.vo.TbUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表(TbUser)表控制层
 *
 * @author makejava
 * @since 2020-07-19 16:19:24
 */
@Api("用户表的操作")
@RestController
@RequestMapping("tbUser")
@CrossOrigin
public class TbUserController {
    /**
     * 服务对象
     */
    @Resource
    private TbUserService tbUserService;
    @Autowired
    private RedisUtil redisUtil;
    @ApiOperation(value = "用户表查询",notes = "对用户表的所有数据展示")
    /**
     * 查询用户表全部
     * @return
     */
    @GetMapping("/findAll")
    public Result01 findAll(){
        /*try {
            int a=1/0;
        } catch (Exception e) {
            //手动抛出业务异常
            throw new BusinessException(20001,"算术异常");
        }*/
        List<TbUser> list = tbUserService.list();
        return Result01.ok().data("users",list);
    }

    @ApiOperation(value = "用户表分页条件查询",notes = "分页+条件查询")
    @PostMapping("/findByPageOrTbUserVo/{current}/{size}")
    public Result02 findByPageOrTbUserVo(@PathVariable("current") Integer current,@PathVariable("size") Integer size,@RequestBody(required = false) TbUserVo tbUserVo){
        System.out.println(current);
        Page<TbUser> page = tbUserService.findByPageOrTbUserVo(current, size, tbUserVo);
        Map<String,Object> map=new HashMap<>();
        if(page.getTotal()==0){
            throw new BusinessException(20000,"无用户信息");
        }else {
            map.put("total",page.getTotal());
            map.put("size",page.getSize());
            map.put("hasPrevious",page.hasPrevious());
            map.put("hasNext",page.hasNext());
            map.put("current",page.getCurrent());
            map.put("users",page.getRecords());
        }
        return Result02.success().data(map);
    }
    /**
     * 登录
     * @return
     */
    @ApiOperation(value = "登录操作",notes = "用户操作")
    @PostMapping("/login")
    public Result02 login(@RequestParam(required = false) String username, @RequestParam(required = false) String password
            ,@RequestParam(required = false) String code,HttpServletRequest request){

        System.out.println(username+"--"+password+"前端code"+code);
        // 获取 redis 中的验证码
        String captchaCode = (String) redisUtil.get("captcha");
        System.out.println(captchaCode+"==>验证码");
        // 判断验证码
        if (code==null || captchaCode!=null&&!captchaCode.equals(code.trim().toLowerCase())) {
            return Result02.fail().message("验证码不正确");
        }else {
            //生成token
            String token = tbUserService.loginUser(username, password);
            if(token!=null){
                Map<String,Object> map=new HashMap<>();
                map.put("token",token);
                return Result02.success().data(map).message("登录成功！");
            }else {
                return Result02.fail().message("登录失败！");
            }
        }

    }

    @GetMapping("/info")
    public Result02 info(String token){
        JwtToken jwtToken=new JwtToken();
        String username = jwtToken.parseJwt(token);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        TbUser user = tbUserService.getOne(queryWrapper);
        Map<String,Object> map=new HashMap<>();
        map.put("name",user.getNickname());
        map.put("avatar",user.getAvatar());
        System.out.println("执行了方法");
        return Result02.success().data(map);
    }

    /**
     * 根据id查询用户
     */
    @ApiOperation(value = "用户查询",notes = "根据id进行用户查询")
    @GetMapping("findById")
    public Result01 findById(@RequestParam(required = false) Integer id){
        TbUser u = tbUserService.getById(id);
        if(u==null){
            throw new BusinessException(20001,"用户不存在！亲！");
        }
        return Result01.ok().data("user",u);
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @ApiOperation(value = "删除操作",notes = "根据id进行删除")
    @DeleteMapping("/removeById/{id}")
    public Result02 removeById(@PathVariable("id") Integer id){
        System.out.println("进来了"+id);
       boolean b = tbUserService.removeById(id);
        System.out.println("出去了");
       if(b){
           return Result02.success().data("删除成功！");
       }else {
           return Result02.fail().data("删除失败！");
       }
   }

    /**
     * 修改操作
     * @param user
     * @return
     */
    @ApiOperation(value = "用户修改",notes = "根据编号进行修改")
    @PutMapping("/updUser")
    public Result02 updUser(@RequestBody(required = false) TbUser user){
        System.out.println(user+"修改");
        boolean b = tbUserService.updateById(user);
        if(b){
            return Result02.success().message("修改成功！").data("jj");
        }else {
            return Result02.fail().message("修改失败！");
        }
    }


    @ApiOperation(value = "用户增加",notes = "增加用户信息/注册")
    @PostMapping("/instUser")
    public Result02 instUser(@RequestBody(required = false) TbUser user){
        System.out.println("增加的用户信息："+user);
        Integer user1 = tbUserService.instUser(user);
        System.out.println(user+"增加");
        if(user1>0){
            return Result02.success().message("增加成功！");
        }else {
            return Result02.fail().message("增加失败！");
        }
    }
    @ApiOperation(value = "是否禁用用户",notes = "根据id禁用")
    @PostMapping("/updStatusById")
    public Result02 updStatusById(Integer id,Integer status){
        Boolean sts = tbUserService.updStatusById(id, status);
        if(sts){
            return Result02.success().message("修改成功！");
        }else {
            return Result02.fail().message("修改失败！");
        }
    }
    @ApiOperation(value = "导出清单", notes = "export", produces = "application/octet-stream")
    @RequestMapping(value = "/downloadExcel",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadExcel(HttpServletResponse response,@RequestBody(required = false) TbUserVo tbUserVo) throws IOException {
        System.out.println(tbUserVo);
        tbUserService.download(response,tbUserVo);
    }

    @ApiOperation(value = "注销")
    @PostMapping("/loginOut")
    public Result02 loginOut(){
        return Result02.success();
    }

    /**
     * 图形验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);

        // 验证码存入redis 默认120s过期
        redisUtil.set("captcha", specCaptcha.text().toLowerCase(),120);
        // 输出图片流
        specCaptcha.out(response.getOutputStream());
    }
}